<template>
  <div class="department-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>科室管理</span>
          <el-button
            type="primary"
            size="small"
            class="add-department-btn"
            @click="handleAddDepartment"
          >
            新增科室
          </el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="24">
          <div class="search-container">
            <el-input
              v-model="searchQuery"
              placeholder="输入科室名称搜索"
              prefix-icon="Search"
              class="search-input"
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="departmentsData"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="科室ID" width="80" />
        <el-table-column prop="name" label="科室名称" width="180" />
        <el-table-column prop="hospitalName" label="所属医院" width="180" />
        <el-table-column prop="description" label="科室描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditDepartment(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteDepartment(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑科室对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="departmentFormRef"
        :model="departmentForm"
        :rules="departmentRules"
        label-width="100px"
      >
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select
            v-model="departmentForm.hospitalId"
            placeholder="请选择医院"
          >
            <el-option
              v-for="hospital in hospitals"
              :key="hospital.id"
              :label="hospital.name"
              :value="hospital.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科室描述" prop="description">
          <el-input
            v-model="departmentForm.description"
            type="textarea"
            placeholder="请输入科室描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
// 假设我们有这些API接口
// import {
//   getDepartments,
//   addDepartment,
//   updateDepartment,
//   deleteDepartment,
//   getHospitals
// } from '@/api/department';

// 表格数据
const departmentsData = ref<Array<any>>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchQuery = ref('');

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增科室');
const departmentFormRef = ref<any>(null);
const departmentForm = reactive({
  id: 0,
  name: '',
  hospitalId: 0,
  description: ''
});
const departmentRules = {
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 2, max: 20, message: '科室名称长度在2-20个字符之间', trigger: 'blur' }
  ],
  hospitalId: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ]
};

// 医院列表（用于下拉选择）
const hospitals = ref<Array<any>>([]);

// 页面加载时获取数据
onMounted(() => {
  fetchHospitals();
  fetchDepartments();
});

// 获取医院列表
const fetchHospitals = async () => {
  try {
    loading.value = true;
    // 实际项目中调用API
    // const res = await getHospitals();
    // 模拟数据
    hospitals.value = [
      { id: 1, name: '北京协和医院' },
      { id: 2, name: '北京朝阳医院' },
      { id: 3, name: '北京积水潭医院' }
    ];
  } catch (error) {
    ElMessage.error('获取医院列表失败');
    console.error('获取医院列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取科室列表
const fetchDepartments = async () => {
  try {
    loading.value = true;
    // 实际项目中调用API
    // const res = await getDepartments({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchQuery.value
    // });
    // 模拟数据
    const mockData = Array.from({ length: 20 }, (_, index) => ({
      id: index + 1,
      name: `科室${index + 1}`,
      hospitalName: hospitals.value[index % hospitals.value.length]?.name || '未知医院',
      hospitalId: hospitals.value[index % hospitals.value.length]?.id || 0,
      description: `这是${index + 1}科室的详细描述信息。`,
      status: Math.random() > 0.5 ? 1 : 0
    }));
    departmentsData.value = mockData;
    total.value = 100;
  } catch (error) {
    ElMessage.error('获取科室列表失败');
    console.error('获取科室列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索科室
const handleSearch = () => {
  currentPage.value = 1;
  fetchDepartments();
};

// 新增科室
const handleAddDepartment = () => {
  dialogTitle.value = '新增科室';
  Object.keys(departmentForm).forEach(key => {
    departmentForm[key as keyof typeof departmentForm] = '';
  });
  departmentForm.id = 0;
  dialogVisible.value = true;
};

// 编辑科室
const handleEditDepartment = (row: any) => {
  dialogTitle.value = '编辑科室';
  Object.assign(departmentForm, row);
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await departmentFormRef.value.validate();
    if (valid) {
      loading.value = true;
      if (departmentForm.id) {
        // 编辑科室
        // await updateDepartment(departmentForm);
        ElMessage.success('编辑科室成功');
      } else {
        // 新增科室
        // await addDepartment(departmentForm);
        ElMessage.success('新增科室成功');
      }
      dialogVisible.value = false;
      fetchDepartments();
    }
  } catch (error) {
    ElMessage.error('提交失败，请检查表单');
    console.error('提交失败:', error);
  } finally {
    loading.value = false;
  }
};

// 删除科室
const handleDeleteDepartment = async (id: number) => {
  try {
    // 实际项目中调用API
    // await deleteDepartment(id);
    ElMessage.success('删除科室成功');
    fetchDepartments();
  } catch (error) {
    ElMessage.error('删除科室失败');
    console.error('删除科室失败:', error);
  }
};

// 切换状态
const handleStatusChange = async (row: any) => {
  try {
    // 实际项目中调用API更新状态
    // await updateDepartment({
    //   id: row.id,
    //   status: row.status
    // });
    ElMessage.success('状态更新成功');
  } catch (error) {
    // 回滚状态
    row.status = !row.status;
    ElMessage.error('状态更新失败');
    console.error('状态更新失败:', error);
  }
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchDepartments();
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  fetchDepartments();
};
</script>

<style scoped lang="scss">
.department-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  .search-input {
    width: 300px;
    margin-right: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>